package com.huxiu.yd.fragments;

import android.app.Fragment;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.view.LayoutInflater;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.android.volley.Request.Method;
import com.android.volley.Response.ErrorListener;
import com.android.volley.Response.Listener;
import com.android.volley.VolleyError;
import com.handmark.pulltorefresh.library.PullToRefreshBase;
import com.handmark.pulltorefresh.library.PullToRefreshBase.OnRefreshListener2;
import com.handmark.pulltorefresh.library.PullToRefreshBase.State;
import com.handmark.pulltorefresh.library.PullToRefreshListView;
import com.huxiu.yd.R;
import com.huxiu.yd.net.GsonRequest;
import com.huxiu.yd.net.NetworkConstants;
import com.huxiu.yd.net.NetworkHelper;
import com.huxiu.yd.net.model.DiscoveryItem;
import com.huxiu.yd.net.responses.DiscoveryListResponse;
import com.huxiu.yd.utils.Utils;
import com.huxiu.yd.view.DiscoveryViewHolder;
import com.nostra13.universalimageloader.core.ImageLoader;
import com.nostra13.universalimageloader.core.listener.PauseOnScrollListener;

import java.util.ArrayList;
import java.util.Collections;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import butterknife.ButterKnife;
import butterknife.InjectView;

/**
 * Created by kHRYSTAL on 15/9/18:下午2:45.
 */
public class MassiveTestFragment extends Fragment implements OnClickListener,
        OnRefreshListener2<ListView> {

    @InjectView(R.id.back)
    ImageView back;

    @InjectView(R.id.left_text)
    TextView leftText;

    @InjectView(R.id.title)
    TextView title;

    @InjectView(R.id.right_image)
    ImageView rightImage;

    @InjectView(R.id.right_text)
    TextView rightText;

    @InjectView(R.id.list)
    PullToRefreshListView list;

    private MassiveTestAdapter adapter;

    private boolean isMine = false;

    private boolean isTopic = false;

    private String userId;

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, ViewGroup container,
                             Bundle savedInstanceState) {
        View view = inflater.inflate(R.layout.fragment_discovery, container, false);
        ButterKnife.inject(this, view);
        Bundle bundle = getArguments();
        if (bundle != null) {
            isMine = bundle.getBoolean("mine", false);
            isTopic = bundle.getBoolean("topic", false);
            userId = bundle.getString("user_id", null);
        }
        if (isMine || isTopic) {
            view.findViewById(R.id.header).setVisibility(View.GONE);
        } else {
            back.setVisibility(View.GONE);
            rightImage.setVisibility(View.GONE);
            title.setText(R.string.massive_test);
        }
        adapter = new MassiveTestAdapter();
        list.setAdapter(adapter);
        list.setOnRefreshListener(this);
        list.setState(State.INIT_REFRESHING, true);
        PauseOnScrollListener listener = new PauseOnScrollListener(ImageLoader.getInstance(), false,
                true);
        list.setOnScrollListener(listener);
        return view;
    }

    @Override
    public void onDestroyView() {
        super.onDestroyView();
        ButterKnife.reset(this);
        NetworkHelper.getInstance().getRequestQueue().cancelAll(this);
    }

    private void refreshComplete() {
        if (list != null)
            list.postDelayed(new Runnable() {
                @Override
                public void run() {
                    list.onRefreshComplete();
                }
            }, 100);
    }

    @Override
    public void onClick(View v) {

    }

    @Override
    public void onPullDownToRefresh(PullToRefreshBase<ListView> refreshView) {
        getItems(0);
    }

    @Override
    public void onPullUpToRefresh(PullToRefreshBase<ListView> refreshView) {
        getItems(currentPage + 1);
    }

    private List<DiscoveryItem> items = new ArrayList<>();

    private class MassiveTestAdapter extends BaseAdapter {

        @Override
        public int getCount() {
            return items.size();
        }

        @Override
        public DiscoveryItem getItem(int position) {
            return items.get(position);
        }

        @Override
        public long getItemId(int position) {
            return 0;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            DiscoveryViewHolder holder;
            View view = convertView;
            if (view == null) {
                view = getActivity().getLayoutInflater()
                        .inflate(R.layout.discovery_list_item, parent, false);
                holder = new DiscoveryViewHolder(view, getActivity(),
                        DiscoveryViewHolder.TYPE_MASSIVE_TEST);
                view.setTag(holder);
            }
            holder = (DiscoveryViewHolder) view.getTag();
            DiscoveryItem item = getItem(position);
            holder.bindDiscoveryItem(item);
            return view;
        }
    }

    private int currentPage = 0;

    private void getItems(final int page) {
        String url = isMine || isTopic ? NetworkConstants.MEMBER_URL : NetworkConstants.TOPIC_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("page", Integer.toString(page));
        String act = "lists";
        if (isMine) {
            act = "my_favorite";
        }
        if (isTopic) {
            act = "user_topic";
        }
        params.put("act", act);
        if (!TextUtils.isEmpty(userId)) {
            params.put("other_user_id", userId);
        }
        if (isMine) {
            params.put("opt", "topic_activity");
        }
        GsonRequest<DiscoveryListResponse> request = new GsonRequest<>(url, Method.POST,
                DiscoveryListResponse.class, true, params,
                new Listener<DiscoveryListResponse>() {
                    @Override
                    public void onResponse(DiscoveryListResponse response) {
                        if (response.isSuccess()) {
                            if (page == 0) {
                                items.clear();
                            }
                            if (list != null)
                                if (response.page == response.max_page) {
                                    list.setMode(PullToRefreshBase.Mode.PULL_FROM_START);
                                } else {
                                    list.setMode(PullToRefreshBase.Mode.BOTH);
                                }
                            Collections.addAll(items, response.data);
                            adapter.notifyDataSetChanged();
                            currentPage = response.page;
                        } else {
                            Utils.showToast(response.msg);
                        }
                        refreshComplete();
                    }
                }, new ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError volleyError) {
                refreshComplete();
            }
        });
        NetworkHelper.getInstance().addToRequestQueue(request);
//        NetworkHelper.getInstance().getRequestQueue().start();
    }
}
